#include "common/ntp/timeNTP.h"

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "cn.ntp.org.cn", 3600, 60000);

int tryNtpServers()
{
    char *arr[] = {(char *)"cn.ntp.org.cn", (char *)"cn.pool.ntp.org", (char *)"ntp.aliyun.com", (char *)"ntp.ntsc.ac.cn", (char *)"ntp.tencent.com", (char *)"time.edu.cn"};
    unsigned char count = 0;

    for (char *server : arr)
    {
        ESP.wdtFeed();

        timeClient.setPoolServerName(server);
        timeClient.setTimeOffset(8 * 3600);
        timeClient.begin();
        timeClient.update();

        if (timeClient.isTimeSet())
        {
            timeClient.end();
            return count;
        }

        count++;
        delay(500);
    };

    timeClient.end();
    return -1;
}

int InitNTP()
{
    if (0 > tryNtpServers())
    {
        return 0;
    }

    return 1;
}

int NTPupdate()
{
    if (0 > tryNtpServers())
    {
        return 0;
    }
    return 1;
}

String getDateTime()
{
    return timeClient.getFormattedTime();
}

String getTime()
{
    return timeClient.getFormattedTime();
}

String getHMTime()
{
    unsigned long rawTime = timeClient.getEpochTime();
    unsigned long hours = (rawTime % 86400L) / 3600;
    String hoursStr = hours < 10 ? "0" + String(hours) : String(hours);

    unsigned long minutes = (rawTime % 3600) / 60;
    String minuteStr = minutes < 10 ? "0" + String(minutes) : String(minutes);

    unsigned long seconds = rawTime % 60;
    String secondStr = seconds < 10 ? "0" + String(seconds) : String(seconds);

    return hoursStr + ":" + minuteStr;
}

String getMSTime()
{
    unsigned long rawTime = timeClient.getEpochTime();
    unsigned long hours = (rawTime % 86400L) / 3600;
    String hoursStr = hours < 10 ? "0" + String(hours) : String(hours);

    unsigned long minutes = (rawTime % 3600) / 60;
    String minuteStr = minutes < 10 ? "0" + String(minutes) : String(minutes);

    unsigned long seconds = rawTime % 60;
    String secondStr = seconds < 10 ? "0" + String(seconds) : String(seconds);

    return minuteStr + ":" + secondStr;
}

void showDateTime()
{
    Serial.println(getDateTime());
}

int hour()
{
    unsigned long rawTime = timeClient.getEpochTime();
    unsigned long hh = (rawTime % 86400L) / 3600;

    return hh;
}

int minute()
{
    unsigned long rawTime = timeClient.getEpochTime();
    unsigned long mm = (rawTime % 3600) / 60;

    return mm;
}

int second()
{
    unsigned long rawTime = timeClient.getEpochTime();
    int ss = rawTime % 60;

    return ss;
}

unsigned long rawTime()
{
    return timeClient.getEpochTime();
}